﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Client;
using System.Collections;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.ComponentModel;
using System.Threading;

namespace SmallTfs
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        bool acumulateTaskListForExport = false;
        Dictionary<int, TaskItem> exporttzaskList = new Dictionary<int, TaskItem>();
        string currentBranchRoot;
        string projectName = String.Empty;
        List<string> BranchList = new List<string>();
        string currentfolder = "";
        TeamFoundationServer tfs = null;
        VersionControlServer versionControl = null;
        Workspace workspace = null;
        private bool connected = false;
        
        public MainWindow()
        {
            InitializeComponent();
            StaticConfManager.CManager = new ConfManager();
            this.DataContext = StaticConfManager.CManager;
            currentBranchRoot = StaticConfManager.CManager.RootMergePath;
        }

        private void bntConnect_Click(object sender, RoutedEventArgs e)
        {

            ProgressDialog dlg = new ProgressDialog();
            dlg.Owner = this;
            dlg.AutoIncrementInterval = 200;
            int startValue = 1;

            string tfsName = txtServerUrl.Text;
            string tfsproject = txtProjectName.Text;
            string tfsProjectpath = txtMapProjectPath.Text;
            string tfsWorkspaceName = txtWorkSpaceName.Text;

            projectName = tfsproject;
            dlg.RunWorkerThread(startValue, delegate(object sender1, DoWorkEventArgs e1)
            {
                InitializeTFSAndLoadTree(tfsName, tfsproject, tfsProjectpath, tfsWorkspaceName);
            });

        }

        private void InitializeTFSAndLoadTree(string tfsName, string tfsProject, string tfsprojectPath, string tfsWorkspaseName)
        {

            tfs = new TeamFoundationServer(tfsName);

            versionControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
            versionControl.NonFatalError += new ExceptionEventHandler(versionControl_NonFatalError);
            versionControl.Getting += new GettingEventHandler(versionControl_Getting);
            versionControl.BeforeCheckinPendingChange += new ProcessingChangeEventHandler(versionControl_BeforeCheckinPendingChange);
            versionControl.NewPendingChange += new PendingChangeEventHandler(versionControl_NewPendingChange);

            try
            {
                workspace = versionControl.GetWorkspace(tfsWorkspaseName, versionControl.AuthenticatedUser);

            }
            catch (Exception ex)
            {
                workspace = versionControl.CreateWorkspace(tfsWorkspaseName, versionControl.AuthenticatedUser);
            }
            try
            {
                workspace.Map(tfsProject, tfsprojectPath);
                RefreshFolderList();
                LoadBranchesList("");

                GetLabelDefinitions(tfsProject);
            }
            catch (Exception ex)
            {

                Dispatcher.Invoke(
                System.Windows.Threading.DispatcherPriority.Normal,
                new Action(
                 delegate()
                 {
                     txtStatus.Text = "Error: " + ex.Message;
                 }
                 ));


            }
        }

        private void RefreshFolderList()
        {

            Dispatcher.Invoke(
             System.Windows.Threading.DispatcherPriority.Normal,
             new Action(
              delegate()
              {
                  tFolders.Items.Clear();
                  TreeViewItem itm = new TreeViewItem();
                  itm.Header = txtProjectName.Text;

                  RefreshFolderList(itm.Header as string, ref itm);

              }
           ));

        }

        private void RefreshFolderList(string name, ref TreeViewItem item)
        {
            ItemSpec iSpec = new ItemSpec(name, RecursionType.Full);
            ItemSet theSet = versionControl.GetItems(iSpec, VersionSpec.Latest, DeletedState.NonDeleted, ItemType.Folder, false);

            List<TFSFolder> folders = (from f in theSet.Items
                                       select new TFSFolder()
                                       {
                                           Path = f.ServerItem
                                       }).ToList();


            List<TFSFolder> retList = new List<TFSFolder>();
            while (true)
            {
                if (folders.Count == 0)
                    break;

                TFSFolder fld = folders[0];

                folders.Remove(fld);

                List<TFSFolder> tmpList = (from f1 in folders
                                           where f1.Path.Contains(fld.Path)
                                           select f1).ToList();

                folders.RemoveAll(x => x.Path.Contains(fld.Path));

                fld.ChildFolders = tmpList;

                retList.Add(fld);
            }


            tFolders.Items.Clear();


            TreeViewItem itemX = new TreeViewItem();
            itemX.Header = "Src";

            LoadTree(retList, ref itemX);

            tFolders.Items.Add(itemX);

            PendingChange[] pendingChanges = workspace.GetPendingChanges();
            grdPendingChanges.ItemsSource = pendingChanges;

        }

        private void LoadTree(List<TFSFolder> retList, ref TreeViewItem parentItem)
        {
            foreach (var f in retList)
            {
                TreeViewItem item = new TreeViewItem();
                item.Header = f.Name;
                item.Tag = f.Path;

                LoadTree(f.ChildFolders, ref item);
                parentItem.Items.Add(item);

            }
        }

        private static void CreateDir(ref Workspace workspace)
        {

            WidnowCreateDir win = new WidnowCreateDir();
            win.Title = "Create folder [enter folder name]";
            win.ShowDialog();
            if (String.IsNullOrEmpty(win.PathName))
                return;

            string pathname = win.PathName;

            String topDir = System.IO.Path.Combine(workspace.Folders[0].LocalItem, pathname);
            Directory.CreateDirectory(topDir);

            workspace.PendAdd(topDir, true);
        }

        void versionControl_NewPendingChange(object sender, PendingChangeEventArgs e)
        {
            txtStatus.Text = e.PendingChange.FileName + " pending change";
            PendingChange[] pendingChanges = workspace.GetPendingChanges();
            grdPendingChanges.ItemsSource = pendingChanges;
        }

        void versionControl_BeforeCheckinPendingChange(object sender, ProcessingChangeEventArgs e)
        {
            txtStatus.Text = e.PendingChange.FileName + " process pending change";
            PendingChange[] pendingChanges = workspace.GetPendingChanges();
            grdPendingChanges.ItemsSource = pendingChanges;
        }

        void versionControl_Getting(object sender, GettingEventArgs e)
        {
            txtStatus.Text = e.ServerItem + " getting";
        }

        void versionControl_NonFatalError(object sender, Microsoft.TeamFoundation.VersionControl.Client.ExceptionEventArgs e)
        {
            txtStatus.Text = e.Failure.LocalItem + " failure:" + e.Failure.Message;
        }

        private void btnCheckWorkSpace_Click(object sender, RoutedEventArgs e)
        {

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            CreateDir(ref workspace);
            RefreshFolderList();
        }

        private void tFolders_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (tFolders.SelectedItem == null)
                return;

            currentfolder = ((TreeViewItem)tFolders.SelectedItem).Tag as string;

            ProgressDialog dlg = new ProgressDialog();
            dlg.Owner = this;
            dlg.AutoIncrementInterval = 200;
            int startValue = 1;

            dlg.RunWorkerThread(startValue, delegate(object sender1, DoWorkEventArgs e1)
            {
                RefreshFileList(currentfolder);
            });

        }

        private void RefreshFileList(string currentfolder)
        {
            if (String.IsNullOrEmpty(currentfolder))
                return;


            Dispatcher.Invoke(
           System.Windows.Threading.DispatcherPriority.Normal,
           new Action(
            delegate()
            {
                LoadBrachTree(currentfolder);
            }
            ));




            ItemSpec iSpec = new ItemSpec(currentfolder, RecursionType.OneLevel);
            ItemSet itms = versionControl.GetItems(iSpec, VersionSpec.Latest, DeletedState.NonDeleted, ItemType.File, true);
            if (itms.Items.Count() == 0)
                return;

            ItemSpec[] itemsSpec = (from i in itms.Items
                                    select new ItemSpec(i.ServerItem, RecursionType.OneLevel)).ToArray();

            string[] filesPaths = (from i in itms.Items
                                   select i.ServerItem).ToArray();

            ExtendedItem[][] theSet = versionControl.GetExtendedItems(itemsSpec, DeletedState.NonDeleted, ItemType.File, GetItemsOptions.IncludeSourceRenames);


            PendingSet[] sets = versionControl.QueryPendingSets(filesPaths, RecursionType.Full, null, null);


            var pSets = (from s1 in sets
                         from s2 in s1.PendingChanges
                         select new
                         {
                             ComputerName = s1.Computer,
                             OwnerName = s1.OwnerName,
                             Name = s1.Name,
                             ServerItem = s2.ServerItem,
                             Filename = s2.FileName,
                             Version = s2.Version
                         }).ToList();


            List<DisplayItem> xItems = new List<DisplayItem>();


            if (pSets.Count() > 0)
            {

                xItems = (from xi in theSet
                          where pSets.Count(x => x.ServerItem == ((ExtendedItem)xi[0]).SourceServerItem) == 0
                          select new DisplayItem(xi[0], "", "")).ToList();


                int sCount = xItems.Count;

                xItems.AddRange((from xi in theSet
                                 from s in pSets
                                 where ((ExtendedItem)xi[0]).SourceServerItem == s.ServerItem
                                 select new DisplayItem(xi[0], s.OwnerName, s.ComputerName)).ToList());

                int xCount = xItems.Count;

            }
            else
            {
                xItems = (from xi in theSet
                          select new DisplayItem(xi[0], "", "")).ToList();


            }

            Dispatcher.Invoke(
            System.Windows.Threading.DispatcherPriority.Normal,
            new Action(
             delegate()
             {
                 lstFiles.ItemsSource = xItems;
             }
         ));


        }

        private void LoadBrachTree(string currentfolder)
        {


            BranchHistoryTreeItem[][] _BranchHistory = versionControl.GetBranchHistory(new ItemSpec[] {
                new ItemSpec(currentfolder,RecursionType.OneLevel)}, LatestVersionSpec.Latest);


            double top = 10;
            double left = 200;
            int countName = 0;
            int currentLevel = -1;
            cnBranches.Children.Clear();


            //countName++;
            //Label lbl = new Label();
            //lbl.Name = "lblBranchN" + countName;
            ////lbl.Background = new SolidColorBrush(
            //lbl.Content = _BranchHistory[0].Relative.BranchToItem.ServerItem;
            //lbl.SetValue(TopProperty, top);
            //lbl.SetValue(LeftProperty, _BranchHistory[0].Level * 200);
            //top += 25;
            //cnBranches.Children.Add(lbl);

            foreach (BranchHistoryTreeItem _Item in _BranchHistory[0])
                ManageBranchTree(ref top, ref countName, _Item);



            //foreach (BranchHistoryTreeItem _Item in _BranchHistory[0])
            //{
            //    //if (_Item.Level != currentLevel)
            //    //{
            //    //    top = 10;
            //    //    currentLevel = _Item.Level;
            //    //    left += 200;
            //    //}

            //    countName++;
            //    Label lbl = new Label();
            //    lbl.Name = "lblBranchN" + countName;
            //    //lbl.Background = new SolidColorBrush(
            //    lbl.Content = _Item.Relative.BranchToItem.ServerItem;
            //    lbl.SetValue(TopProperty, top);
            //    lbl.SetValue(LeftProperty, _Item.Level * left);
            //    top += 30;
            //    cnBranches.Children.Add(lbl);

            //    foreach(
            //}



        }

        private void ManageBranchTree(ref double top, ref int countName, BranchHistoryTreeItem branchHistoryTreeItem)
        {



            foreach (BranchHistoryTreeItem item in branchHistoryTreeItem.Children)
            {
                countName++;
                Label lbl = new Label();
                lbl.Name = "lblBranchN" + countName;
                //lbl.Background = new SolidColorBrush(
                lbl.Content = item.Relative.BranchToItem.ServerItem;
                lbl.SetValue(TopProperty, top);
                lbl.SetValue(LeftProperty, item.Level * 150.0);
                top += 25;
                cnBranches.Children.Add(lbl);

                foreach (BranchHistoryTreeItem vr in branchHistoryTreeItem.Children)
                    ManageBranchTree(ref top, ref countName, vr);
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            //System.Windows.Data.CollectionViewSource itemViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("itemViewSource")));
            // Load data by setting the CollectionViewSource.Source property:
            // itemViewSource.Source = [generic data source]
        }

        private void btnCheckout_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                btnGetLatest_Click(sender, e);

                var o = sender;
                var context = ((Button)sender).DataContext as DisplayItem;


                workspace.PendEdit(context.ServerItem);

                tFolders_SelectedItemChanged(sender, null);


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnGetLatest_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var o = sender;
                var context = ((Button)sender).DataContext as DisplayItem;

                GetRequest request = new GetRequest(new ItemSpec(context.ServerItem, RecursionType.Full), VersionSpec.Latest);
                GetStatus status = workspace.Get(request, GetOptions.GetAll | GetOptions.Overwrite);

                tFolders_SelectedItemChanged(sender, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCheckIn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var o = sender;
                var context = ((Button)sender).DataContext as PendingChange;

                if (context == null)
                    return;

                workspace.PendEdit(context.ServerItem);

                tFolders_SelectedItemChanged(sender, null);


                PendingChange[] pendingChanges = new PendingChange[] {
                    context
                };

                WidnowCreateDir win = new WidnowCreateDir();
                win.Title = "Insert Comment for Check In";
                win.ShowDialog();
                if (String.IsNullOrEmpty(win.PathName))
                    return;


                int changesetNumber = workspace.CheckIn(pendingChanges, win.PathName);

                pendingChanges = workspace.GetPendingChanges();
                grdPendingChanges.ItemsSource = pendingChanges;


                tFolders_SelectedItemChanged(sender, null);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            //GetAssociatedTasks(txtFrom.Text, txtTo.Text, currentfolder);
        }


        public void GetAllChangesetsForDeploy(string path, LabelSpec labelspec)
        {

            List<ChangesetX> ReturnList = new List<ChangesetX>();

            List<Changeset> currentCH = GetCurrentChangesWithDettails(path, labelspec.StartId, labelspec.EndId, true);

            List<ChangesetX> chX = (from c in currentCH
                                    let src = GetrelatedBranch(c.ChangesetId)
                                    where src != "" 
                                    select new ChangesetX(c)
                                    {
                                        Source = src,
                                        ParentSource = path
                                    }).ToList();


            ReturnList.AddRange(chX);
            var chX1 = from c in chX
                       where !c.IsLocal
                       select c;

            //foreach (ChangesetX cx1 in chX1)
            //    GetAllChangesetsRecursion(ref ReturnList, labelspec.StartId, cx1);

          labelspec.Tasks = (from s in ReturnList
                               from wi in s.curent.WorkItems
                               where s.curent.WorkItems != null && s.curent.WorkItems.Count() > 0 && wi.State != "Active"
                               select new TaskItem()
                               {
                                   Source = s.Source,
                                   Id = wi.Id,
                                   Revision = wi.Revision,
                                   Type = wi.Type.Name,
                                   TypeSource = GetTypeImageSource(wi.Type.Name),
                                   Title = wi.Title,
                                   AssignTo = wi.Fields["Assigned to"].Value as string,
                                   State = wi.State,
                                   Description = wi.Description,
                                   Reason = wi.Reason,
                                   ChangedBy = wi.ChangedBy,
                                   ChangedDate = wi.ChangedDate,
                                   CreatedBy = wi.CreatedBy,
                                   CratedDate = wi.CreatedDate,
                                   AreaPath = wi.AreaPath,
                                   IterationPath = wi.IterationPath,
                                   Selected = true
                               }).Distinct().ToList();


          if (acumulateTaskListForExport)
          {
              foreach (var t in labelspec.Tasks)
              {
                  if (!exporttzaskList.Keys.Contains(t.Id))
                      exporttzaskList.Add(t.Id, t);
              }

              Dispatcher.Invoke(
               System.Windows.Threading.DispatcherPriority.Normal,
               new Action(
                delegate()
                {

                    grdTaskList.SetDataSource(exporttzaskList.Values.ToList());

                    button1.Content = String.Format("Acumulate tasks for export {0}", exporttzaskList.Count);

                }));

              
          }
            
            
            //Dictionary<int , TaskItem> cleanList = new Dictionary<int,TaskItem>();
            //foreach(TaskItem ti in labelspec.Tasks)
            //{
            //    if(!cleanList.Keys.Contains(ti.Id))
            //        cleanList.Add(ti.Id, ti);
            //}


          //labelspec.Tasks.Clear();

            //foreach(var v in cleanList)
            //    labelspec.Tasks.Add(v.Value);


            Dispatcher.Invoke(
           System.Windows.Threading.DispatcherPriority.Normal,
           new Action(
            delegate()
            {

                foreach (TreeViewItem ti in treeLabels.Items)
                {
                    if (((LabelSpec)ti.Tag).Id == labelspec.Id)
                    {

                        ti.Items.Add(new TaskGrid(labelspec.Tasks));
                        break;
                    }
                }

            }));


        }

        private void GetAllChangesetsRecursion(ref List<ChangesetX> ReturnList, int lastLabelCS, ChangesetX cx1)
        {
            List<Changeset> currentCH = GetCurrentChangesWithDettails(cx1.Source, lastLabelCS, cx1.ChangesetId, false);

            List<ChangesetX> chX = (from c in currentCH
                                    let src = GetrelatedBranch(c.ChangesetId)
                                    where src != ""
                                    select new ChangesetX(c)
                                    {
                                        Source = src,
                                        ParentSource = cx1.Source
                                    }).ToList();


            ReturnList.AddRange(chX);

            var chX1 = from c in chX
                       where !c.IsLocal
                       select c;

            foreach (ChangesetX c11 in chX1)
                GetAllChangesetsRecursion(ref ReturnList, lastLabelCS, c11);

        }

        private List<Changeset> GetCurrentChangesWithDettails(string path, int? minCS, int? maxCS, bool localCall)
        {
            VersionSpec versionFrom = null;
            VersionSpec versionTo = null;


            if (minCS.HasValue)
                versionFrom = VersionSpec.ParseSingleSpec(minCS.Value.ToString(), null);

            if (maxCS.HasValue && maxCS.Value == 0)
                maxCS = null;

            if (maxCS.HasValue)
                versionTo = VersionSpec.ParseSingleSpec(maxCS.Value.ToString(), null);


            ChangesetMergeDetails merges = versionControl.QueryMergesWithDetails(null, null, 0, path, VersionSpec.Latest, 0, versionFrom, versionTo, RecursionType.Full);
            if (merges.Changesets.Count() == 0)
            {
                #region IF there is no merges

                int maxCount = Int32.MaxValue;
                bool includeChanges = true;
                bool slotMode = true;
                bool includeDownloadInfo = false;

                List<Changeset> retVal = new List<Changeset>();

                IEnumerable enumerable = versionControl.QueryHistory(path, localCall ? VersionSpec.Latest : versionTo, 0, RecursionType.Full, null, versionFrom, versionTo, maxCount, includeChanges, slotMode, includeDownloadInfo);
                //IEnumerable enumerable = versionControl.QueryHistory(path, VersionSpec.Latest , 0, RecursionType.Full, null, null, null, maxCount, includeChanges, slotMode, includeDownloadInfo);


                var list = enumerable.GetEnumerator();

                try
                {
                    while (list.MoveNext())
                    {
                        retVal.Add(list.Current as Changeset);
                    }
                }
                catch (Exception ex)
                {
                }

                return retVal;
                #endregion
            }


            if (merges != null && merges.Changesets != null)
                return merges.Changesets.ToList();
            else
                return new List<Changeset>();
        }

        private void GetLabelDefinitions(string scope)
        {

            VersionControlLabel[] labels = versionControl.QueryLabels(null, scope, null, true);
            List<VersionControlLabel> validLabels = (from l in labels
                                                     select l).OrderBy(x => x.LabelId).ToList();

            List<LabelSpec> labelsX = (from v in validLabels
                                       select new LabelSpec
                                       {
                                           Id = v.LabelId,
                                           EndId = v.Items.Max(x => x.ChangesetId),
                                           CheckId = v.Items.Min(x => x.ChangesetId),
                                           Name = String.Format("{0} created {1}", v.Name, v.LastModifiedDate),
                                           Tasks = new List<TaskItem>(),
                                           DateCreated = v.LastModifiedDate
                                       }).ToList().OrderBy(x => x.Id).ToList();


            for (int i = 0; i < labelsX.Count(); i++)
            {
                labelsX[i].StartId = i == 0 ? 1 : labelsX[i - 1].EndId + 1;
            }

            labelsX.Add(new LabelSpec()
            {
                Id = 0,
                StartId = labelsX[labelsX.Count - 1].EndId + 1,
                Name = "...",
                Tasks = new List<TaskItem>()
            });

            Dispatcher.Invoke(
             System.Windows.Threading.DispatcherPriority.Normal,
             new Action(
              delegate()
              {
                  treeLabels.Items.Clear();
                  foreach (LabelSpec ls in labelsX)
                  {
                      TreeViewItem itm = new TreeViewItem();
                      itm.Header = ls.Name;
                      itm.Tag = ls;
                      treeLabels.Items.Add(itm);
                  }

                  //dgCurrentLabel.ItemsSource = labelsX;
              }));
        }

        private int GetLastlabelChangesetId()
        {


            VersionControlLabel[] labels = versionControl.QueryLabels(null, null, null, true);
            var validLabels = from l in labels
                              where l.Items != null && l.Items.Count() > 0
                              select l;

            //VersionControlLabel maxLabelItem = validLabels.OrderByDescending(x=>x.LabelId).ToList()[0];

            //Dispatcher.Invoke(
            //System.Windows.Threading.DispatcherPriority.Normal,
            //new Action(
            // delegate()
            // {
            //     dgCurrentLabel.ItemsSource = validLabels.OrderByDescending(x => x.LabelId).ToList();
            // }));


            var maxChangeSet = (from l in validLabels
                                from i in l.Items
                                select i).Max(x => x.ChangesetId);




            int maxVal = 0;

            if (Int32.TryParse(Convert.ToString(maxChangeSet), out maxVal))
            {
                return maxVal + 1;
            }
            else
            {
                return 1;
            }
        }

        private void GetAssociatedTasks(string from, string to, string path, bool ViewChangesets)
        {
            #region obsolete
            //string sFrom = "1";
            //string sTo = int.MaxValue.ToString();

            //if (!String.IsNullOrEmpty(from))
            //    sFrom = from;

            //if (!String.IsNullOrEmpty(to))
            //    sTo = to;

            //if (String.IsNullOrEmpty(path))
            //    return;



            //int maxCount = Int32.MaxValue;
            //bool includeChanges = true;
            //bool slotMode = true;
            //bool includeDownloadInfo = true;

            //VersionControlLabel[] labels = versionControl.QueryLabels(null, null, null, true);

            //#region display Labels
            ////List<VersionControlLabel> vcLabels = labels.ToList();

            ////var bindElements = (from l in vcLabels
            ////                   select new
            ////                       {
            ////                           Id = l.LabelId,
            ////                           Name = l.Name,
            ////                           OwnerName = l.OwnerName,
            ////                           LastModifiedDate = l.LastModifiedDate,
            ////                           Scope = l.Scope,
            ////                           Comment = l.Comment
            ////                       }).Distinct().ToList();;



            //#endregion
            //var validLabels = from l in labels
            //                  where l.Items != null && l.Items.Count() > 0
            //                  select l;

            //var maxChangeSet = (from l in validLabels
            //                    from i in l.Items
            //                    select i).Max(x => x.ChangesetId);
            //int maxVal = 0;

            //if (Int32.TryParse(Convert.ToString(maxChangeSet), out maxVal))
            //{
            //    if (maxChangeSet > 1)
            //    {
            //        maxChangeSet++;
            //        sFrom = Convert.ToString(maxChangeSet);
            //    }
            //}
            //List<Changeset> retVal = new List<Changeset>();

            //VersionSpec versionFrom = VersionSpec.ParseSingleSpec(sFrom, null);
            //VersionSpec versionTo = VersionSpec.ParseSingleSpec(sTo, null);

            //ChangesetMergeDetails merges = versionControl.QueryMergesWithDetails(null, null, 0, path, VersionSpec.Latest, 0, versionFrom, null, RecursionType.Full);

            //bool IsMerged = false;

            //if (merges == null || merges.Changesets == null || merges.Changesets.Count() == 0)
            //{
            //    #region IF there is no merges
            //    IsMerged = false;
            //    IEnumerable enumerable =
            //                 versionControl.QueryHistory(path,
            //                                 VersionSpec.Latest,
            //                                 0,
            //                                 RecursionType.Full,
            //                                 null,
            //                                 versionFrom,
            //                                 null,
            //                                 maxCount,
            //                                 includeChanges,
            //                                 slotMode,
            //                                 includeDownloadInfo);

            //    var list = enumerable.GetEnumerator();

            //    try
            //    {
            //        while (list.MoveNext())
            //        {
            //            retVal.Add(list.Current as Changeset);
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //    }
            //    #endregion
            //}
            //else
            //{
            //    IsMerged = true;
            //    retVal = merges.Changesets.ToList();
            //}







            //var spitems = from c in retVal
            //              where c.WorkItems != null && c.WorkItems.Count() > 0
            //              select c;

            #endregion

            //List<LabelSpec> retList = GetAllChangesetsForDeploy(path);




            #region obsolete

            //   if (ViewChangesets)
            //   {
            //       var workItems = (from s in retList
            //                        select new
            //                        {
            //                            Source = s.Source,
            //                            Id = s.ChangesetId,
            //                            Revision = "",
            //                            Title = s.curent.Comment,
            //                            AssignTo = "",
            //                            State = "",
            //                            Description = s.curent.CheckinNote,
            //                            Reason = "",
            //                            ChangedBy = "",
            //                            ChangedDate = "",
            //                            CreatedBy = s.curent.Committer,
            //                            CratedDate = s.curent.CreationDate,
            //                            AreaPath = "",
            //                            IterationPath = ""
            //                        }).Distinct().ToList();

            //       Dispatcher.Invoke(
            //   System.Windows.Threading.DispatcherPriority.Normal,
            //   new Action(
            //    delegate()
            //    {
            //        dtShangeSet.ItemsSource = workItems;
            //        //dgLabels.ItemsSource = bindElements;
            //        TabChangeset.IsSelected = true;
            //    }
            //));

            //   }
            //   else
            //   {

            //       var workItems = (from s in retList
            //                        from wi in s.curent.WorkItems
            //                        where s.curent.WorkItems != null || s.curent.WorkItems.Count() > 0
            //                        select new TaskItem()
            //                        {
            //                            Source = s.Source,
            //                            Id = wi.Id,
            //                            Revision = wi.Revision,
            //                            Type = wi.Type.Name,
            //                            TypeSource = GetTypeImageSource(wi.Type.Name),
            //                            Title = wi.Title,
            //                            AssignTo = wi.Fields["Assigned to"].Value,
            //                            State = wi.State,
            //                            Description = wi.Description,
            //                            Reason = wi.Reason,
            //                            ChangedBy = wi.ChangedBy,
            //                            ChangedDate = wi.ChangedDate,
            //                            CreatedBy = wi.CreatedBy,
            //                            CratedDate = wi.CreatedDate,
            //                            AreaPath = wi.AreaPath,
            //                            IterationPath = wi.IterationPath
            //                        }).Distinct().ToList();

            #endregion
            //       Dispatcher.Invoke(
            //   System.Windows.Threading.DispatcherPriority.Normal,
            //   new Action(
            //    delegate()
            //    {
            //        dtShangeSet.ItemsSource = workItems.Distinct();
            //        //dgLabels.ItemsSource = bindElements;
            //        TabChangeset.IsSelected = true;
            //    }
            //));

            //   }




        }

        private string GetTypeImageSource(string p)
        {

            switch (p)
            {
                case "ISPC Task": { return "/Images/Task.png"; }
                case "ISPC Bug": { return "/Images/Bug.png"; }
                case "ISPC TeamTrack": { return "/Images/TeamTrack.png"; }
                default:
                    {
                        return null;
                    }

            }
        }

        public void LoadBranchesListX(string root)
        {
            ItemIdentifier[] iIdent = versionControl.QueryMergeRelationships(root);
            foreach (ItemIdentifier i in iIdent)
            {
                if (!BranchList.Contains(i.Item))
                {
                    BranchList.Add(i.Item);
                    LoadBranchesListX(i.Item);
                }
            }
        }

        public void LoadBranchesList(string root)
        {
            if (currentBranchRoot == null)
                return;

            //string rootBranch = "$/Demo1/sub/";

            ItemIdentifier[] iIdent = versionControl.QueryMergeRelationships(currentBranchRoot);
            BranchList.Add(currentBranchRoot);
            foreach (ItemIdentifier i in iIdent)
            {
                if (!BranchList.Contains(i.Item))
                {
                    BranchList.Add(i.Item);
                    LoadBranchesListX(i.Item);
                }
            }
        }

        private string GetrelatedBranch(int changesetId)
        {

            Changeset _changeset = versionControl.GetChangeset(changesetId);

            if (_changeset == null || _changeset.Changes == null || _changeset.Changes.Count() == 0)
                return "";

            foreach (var p in BranchList)
            {
                if (_changeset.Changes[0].Item.ServerItem.Contains(p))
                    return p;
            }
            return "";
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (tFolders.SelectedItem == null)
                return;

            string currentfolder = ((TreeViewItem)tFolders.SelectedItem).Tag as string;
            if (String.IsNullOrEmpty(currentfolder))
                return;


            bool ViewCh = (bool)chkViewChangesets.IsChecked;

            ProgressDialog dlg = new ProgressDialog();
            dlg.Owner = this;
            dlg.AutoIncrementInterval = 200;
            int startValue = 1;

            dlg.RunWorkerThread(startValue, delegate(object sender1, DoWorkEventArgs e1)
            {
                GetAssociatedTasks(null, null, currentfolder, ViewCh);
            });

        }

        private void chkViewChangesets_Click(object sender, RoutedEventArgs e)
        {
            MenuItem_Click(sender, e);
        }

        private void dgCurrentLabel_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {








        }

        private void treeLabels_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (((TreeView)sender).SelectedItem == null)
                return;

            try
            {
                LabelSpec label = ((TreeViewItem)((TreeView)sender).SelectedItem).Tag as LabelSpec;
                if (label == null)
                    return;

                if (String.IsNullOrEmpty(currentfolder))
                    return;


                if (((TreeViewItem)((TreeView)sender).SelectedItem).Items.Count > 0)
                    return;


                ProgressDialog dlg = new ProgressDialog();
                dlg.Owner = this;
                dlg.AutoIncrementInterval = 200;
                int startValue = 1;

                dlg.RunWorkerThread(startValue, delegate(object sender1, DoWorkEventArgs e1)
                {
                    GetAllChangesetsForDeploy(currentfolder, label);
                });
            }
            catch { }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ProgressDialog dlg = new ProgressDialog();
            dlg.Owner = this;
            dlg.AutoIncrementInterval = 200;
            int startValue = 1;
            string tfsproject = txtProjectName.Text;

            dlg.RunWorkerThread(startValue, delegate(object sender1, DoWorkEventArgs e1)
            {
                GetLabelDefinitions(tfsproject);
            });
        }

        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            if (tFolders.SelectedItem == null)
                return;

            string currentfolder = ((TreeViewItem)tFolders.SelectedItem).Tag as string;
            if (String.IsNullOrEmpty(currentfolder))
                return;

            currentBranchRoot = currentfolder;
            StaticConfManager.CManager.RootMergePath = currentBranchRoot;
            LoadBranchesList(currentBranchRoot);
        }


        private void LoadHistory()
        {
            mainHistory.Children.Clear();

            if (String.IsNullOrEmpty(currentfolder))
                return;

            double width = 1200;
            double divider = 0;
            double top = 15;

            int maxCount = Int32.MaxValue;
            bool includeChanges = true;
            bool slotMode = true;
            bool includeDownloadInfo = false;
            
            List<Changeset> retVal = new List<Changeset>();

            ChangesetMergeDetails enumerable = versionControl.QueryMergesWithDetails(null, null, 0, currentfolder, VersionSpec.Latest, 0, null, null, RecursionType.Full);
            
            IEnumerable enumerableX = versionControl.QueryHistory(currentfolder, VersionSpec.Latest, 0, RecursionType.Full, null, null, null, maxCount, includeChanges, slotMode, includeDownloadInfo);

            List<ChangesetX> cSets = new List<ChangesetX>();


            List<Changeset> lstTmp = enumerable.Changesets.ToList();

            IEnumerator enX1 = enumerableX.GetEnumerator();

            if (enX1.Current != null)
                lstTmp.Add(enX1.Current as Changeset);

            while (enX1.MoveNext())
            {
                lstTmp.Add(enX1.Current as Changeset);
            }

            foreach(Changeset ec in lstTmp.Distinct().OrderBy(x=>x.ChangesetId))
            {
                ChangesetX cx = new ChangesetX(ec);
                cx.ParentSource = GetrelatedBranch(cx.ChangesetId);
                cx.Source = currentfolder;
                cSets.Add(cx);
            }

            if (cSets.Count == 0)
                return;

            divider = width / cSets.Count;

            double count = 1;
            foreach (ChangesetX cs in cSets.OrderBy(x=>x.ChangesetId))
            {
                AddPoint(divider, top, count, cs);
                if (!cs.IsLocal)
                {
                    Line lCs = new Line();
                    lCs.Y1 = 0;
                    lCs.X1 = 0;

                    lCs.SetValue(Canvas.TopProperty, top + 3);
                    lCs.SetValue(Canvas.LeftProperty, count * divider + 3);


                    lCs.Stroke = new SolidColorBrush(Colors.Yellow);
                    lCs.Y2 = 70 + 3;
                    lCs.X2 = 0;

                    mainHistory.Children.Add(lCs);

                    AddPoint(divider, top + 70, count, cs);
                }
                else
                {
                    

                }
                count = count + 1;
            }
        }

        private void AddPoint(double divider, double top, double count, ChangesetX cs)
        {
            Ellipse el = new Ellipse();
            
            el.Fill = new SolidColorBrush(cs.IsLocal ? Colors.Green : Colors.Red);
            el.ToolTip = cs.ParentSource;
            el.Height = 6;
            el.Width = 6;
            el.Name = "Ellipse" + count.ToString();
            el.SetValue(Canvas.TopProperty, top);
            el.SetValue(Canvas.LeftProperty, count * divider);
            mainHistory.Children.Add(el);

            AddTopLabel(divider, top, count, cs);
            //AddBottomLabel(divider, top, count, cs.ParentSource);
        }

        private void AddTopLabel(double divider, double top, double count, ChangesetX cs)
        {
            Label lbl = new Label();
            lbl.Name = "Label" + count.ToString();
            lbl.FontSize = 9;
            lbl.Content = cs.ChangesetId.ToString();
            lbl.SetValue(Canvas.TopProperty, top - 9);
            lbl.SetValue(Canvas.LeftProperty, count * divider + 3);
            mainHistory.Children.Add(lbl);
        }

        private void AddBottomLabel(double divider, double top, double count, string message)
        {
            Label lbl = new Label();
            lbl.LayoutTransform = new RotateTransform(45.0);
            lbl.Name = "Label" + count.ToString();
            lbl.FontSize = 9;
            lbl.Content = message;
            lbl.SetValue(Canvas.TopProperty, top + 11);
            lbl.SetValue(Canvas.LeftProperty, count * divider - 3);
            mainHistory.Children.Add(lbl);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            LoadHistory();
        }

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            button1.Content = String.Format("Acumulate tasks for export ");
            acumulateTaskListForExport = true;
            exporttzaskList = new Dictionary<int, TaskItem>();
        }


    }

}
